<script setup lang="ts">
import { useDebounceFn } from '@vueuse/core'
import { ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import BigButton from '@/components/common/BigButton.vue'
import message from '@/components/common/message'
import { PageTable } from '@/components/common/pagetable'
import Select from '@/components/common/Select.vue'
import TextInput from '@/components/common/TextInput.vue'
import { Search } from '@/components/icons'
import { getClassList } from '@/request/class'
import { deleteHomework, getHomeworkList } from '@/request/teacher/homework'
import { useTeacherStore } from '@/store/teacher'

const router = useRouter()

const name = ['状态', '作业名称', '班级', '发布时间', '截止时间', '完成情况', '操作']

// 搜索和筛选参数
const searchKeywords = ref('')
const forceRefresh = ref(0)
const classType = ref('')
const statusType = ref('')

// 班级选项
const classOptions = ref<{ label: string, value: string }[]>([
  { label: '全部班级', value: '' },
])

// 获取教师信息
const teacherStore = useTeacherStore()

// 获取班级列表
async function fetchClassList() {
  try {
    const data = await getClassList({
      school: teacherStore.teacher.school,
    })

    // 展开所有年级的班级
    const allClasses = data.entries.flatMap(entry =>
      entry.classes.map(cls => ({
        label: cls.name,
        value: cls.cid,
      })),
    )

    // 添加全部班级选项
    classOptions.value = [
      { label: '全部班级', value: '' },
      ...allClasses,
    ]
  }
  catch (error) {
    console.error('获取班级列表失败:', error)
    message.error('获取班级列表失败')
  }
}

// 作业数据
const homeworkData = ref<{
  id: string
  classId: string
  status: string
  title: string
  class: string
  publishTime: string
  endTime: string
  completion: {
    percentage: number
    completed: number
    total: number
  }
}[]>([])

// 数据获取函数
async function fetcher(page: number, pageSize: number) {
  const data = await getHomeworkList({
    clazz: classType.value || null,
    pageNum: page,
    pageSize,
    search: searchKeywords.value || null,
    status: statusType.value ? Number(statusType.value) : null,
  })

  homeworkData.value = (data.entry.homeworks ?? []).map(item => ({
    classId: item.classId,
    id: item.id,
    status: item.status === 0 ? '进行中' : '已停止',
    title: item.title,
    class: item.clazz,
    publishTime: new Date(item.publishTime).toLocaleString(),
    endTime: new Date(item.ddl).toLocaleString(),
    completion: {
      percentage: Math.floor((Number(item.completionCount) / Number(item.allCount)) * 100) || 0,
      completed: Number(item.completionCount),
      total: Number(item.allCount),
    },
  }))

  return {
    total: data.entry.total || 0,
    page,
    pageSize,
  }
}

// 防抖处理搜索
const handleFilterUpdate = useDebounceFn(() => forceRefresh.value++, 600)

// 筛选条件变化时重新获取数据
function handleSelectUpdate() {
  forceRefresh.value++
}

function handleCreateHomework() {
  router.push('/homework/edit')
}

// 获取班级列表
teacherStore.addCallback(fetchClassList)

function handleDeleteHomework({ id, classId }: { id: string, classId: string }) {
  deleteHomework({ homeworkId: id, classId }).then(() => {
    message.success('删除成功')
    forceRefresh.value++
  })
}
</script>

<template>
  <div class="min-width-wrapper">
    <div class="content-header">
      作业管理
    </div>
    <div class="card-area filter-options">
      <Select
        v-model:model-value="classType" label="班级:" placeholder="全部班级" :options="classOptions"
        @update:model-value="handleSelectUpdate"
      />
      <Select
        v-model:model-value="statusType" label="状态:" placeholder="全部状态" :options="[{
          label: '全部状态',
          value: '',
        }, {
          label: '进行中',
          value: '0',
        }, {
          label: '已停止',
          value: '1',
        }]" @update:model-value="handleSelectUpdate"
      />
      <TextInput v-model="searchKeywords" label="搜索:" placeholder="作业名称关键词" @update:model-value="handleFilterUpdate">
        <template #suffix>
          <Search />
        </template>
      </TextInput>
    </div>
    <div class="filter-result">
      <PageTable v-model:force-refresh="forceRefresh" :fetcher="fetcher" :default-page-size="4">
        <template #header>
          <div class="header">
            <div v-for="i in name" :key="i" class="header-item">
              {{ i }}
            </div>
          </div>
        </template>
        <template #default>
          <div v-for="(item, index) in homeworkData" :key="index" class="data-row">
            <div class="data-item status-tag">
              <span class="tag" :class="item.status === '进行中' ? 'active-tag' : 'stopped-tag'">
                {{ item.status }}
              </span>
            </div>
            <div class="data-item title" @click="$router.push(`/homework/detail/${item.classId}/${item.id}`)">
              {{ item.title }}
            </div>
            <div class="data-item class">
              {{ item.class }}
            </div>
            <div class="data-item time">
              {{ item.publishTime }}
            </div>
            <div class="data-item time">
              {{ item.endTime }}
            </div>
            <div class="data-item completion">
              <div class="progress-container">
                <div class="progress-bar">
                  <div class="progress-fill" :style="{ width: `${item.completion.percentage}%` }" />
                </div>
                <span class="progress-text">{{ item.completion.percentage }}%({{ item.completion.completed }}/{{
                  item.completion.total }})</span>
              </div>
            </div>
            <div class="data-item actions">
              <span class="action-btn edit-btn">
                <RouterLink :to="`/homework/edit/${item.id}`">
                  编辑
                </RouterLink>
              </span>
              <span class="action-btn delete-btn" @click.stop="handleDeleteHomework(item)">删除</span>
            </div>
          </div>
        </template>
      </PageTable>
    </div>
    <BigButton text="新建作业" @click="handleCreateHomework" />
  </div>
</template>

<style scoped>
.min-width-wrapper {
  min-width: 860px;
}

.card-area.filter-options {
  padding: 18px 12px;
  margin-top: 12px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 25px;
}

.filter-result {
  margin-top: 21px;
  margin-bottom: 58px;
  --grid-style: 70px minmax(6rem, 2fr) 8rem 10rem 10rem 1fr 6rem;

  .header {
    display: grid;
    grid-template-columns: var(--grid-style);

    .header-item {
      padding: 10px 8px;
    }
  }

  .data-row {
    display: grid;
    grid-template-columns: var(--grid-style);
    border-bottom: 1px solid #eaeaea;
    min-height: 50px;
    align-items: center;

    .data-item {
      padding: 10px 8px;
      display: flex;
      align-items: center;

      &.status-tag {
        .tag {
          width: 100%;
          height: 20px;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 1000px;
          font-size: 10px;
          color: white;
          font-weight: 500;
        }

        .active-tag {
          background: linear-gradient(90deg, #284af9 0%, #7a91fe 100%);
        }

        .stopped-tag {
          background-color: #b4b4b4;
        }
      }

      &.title {
        font-size: 14px;
        color: #333;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        position: relative;
        &:hover {
          text-decoration: underline;
          cursor: pointer;
        }
        &::after {
          content: '';
          background-color: #333;
          width: 20%;
          height: 100%;
          position: absolute;
          right: 0;
          background: linear-gradient(to right, #ffffff00, #ffffff);
        }
      }

      &.class {
        font-size: 14px;
        color: #333;
      }

      &.time {
        font-size: 13px;
        color: #666;
      }

      &.completion {
        .progress-container {
          margin-top: 4px;
          width: 100%;
          display: flex;
          align-items: flex-start;
          flex-direction: column;
          gap: 4px;

          .progress-bar {
            width: 90%;
            height: 11px;
            background-color: #e5e7eb;
            border-radius: 30px;
            overflow: hidden;

            .progress-fill {
              height: 100%;
              border-radius: 30px;
              background: linear-gradient(90deg, var(--primary-color) 0%, var(--primary-color-300) 100%);
              transition: width 0.3s ease;
            }
          }

          .progress-text {
            font-size: 10px;
            color: #6e6e6e;
            text-align: center;
          }
        }
      }

      &.actions {
        display: flex;
        gap: 15px;

        .action-btn {
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s;

          &.edit-btn {
            a {
              color: var(--primary-color);
              text-decoration: none;
            }
          }

          &.delete-btn {
            color: var(--text-color);
          }
        }
      }
    }

    &:hover {
      background-color: #fafafa;
    }
  }
}
</style>
